import {Component, Inject, Input, OnInit, Optional} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {OperaRoleModule} from '../../../../service/common.module';
import {UtilityService} from '../../../../service/utils.service';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {ActivatedRoute, Router} from '@angular/router';
import {appConfig} from '../../../../service/common';
import {CommondictServe} from '../../../../service/commonDict';
import * as _ from 'lodash';
import {ReuseTabService} from '@delon/abc';

@Component({
  selector: 'app-role-member',
  templateUrl: './role-member.component.html',
})
export class RoleMemberComponent implements OnInit {


    // @Input() // 输入属性,接受父组件传入的树数据
    // data: any[];

    constructor(
        private http: _HttpClient,
        private router: Router,
        private activatedRoute: ActivatedRoute, // 注入路由，接收到参数
        private nznot: NzNotificationService,
        private modal: NzModalService,
        private utilityService: UtilityService,
        private commondict: CommondictServe,
        @Optional() @Inject(ReuseTabService) private reuseTabService: ReuseTabService,
    ) { }

    operators: OperaRoleModule = new OperaRoleModule(); // 绑定数据
    roleGuid: string;
    loading = false;
    buttons = [
        {key: 'add', value: '分配成员'}
    ]
    configTitle: string; // 操作按钮名称
    total: number; // 总页数
    selectType: string; // 选择员工类型
    orgCode: string; // 组织机构字符串
    orgList: any; // 组织机构列表
    pageIndex = 1; // 当前页数
    roleType: any; //　员工状态
    operType: any; //　操作员状态
    selectedRows: any; // 总数
    modalVisible = false;
    page: any; // 翻页数据
    orgChildList: any;
    data: any[] = []; // 表格数据
    headerData = [  // 配置表头内容
        {value: '操作员姓名', key: 'operatorName',  isclick: false},
        {value: '登录用户名' , key: 'userId', isclick: false},
        {value: '操作员状态' , key: 'operatorStatus', isclick: false}
    ];

    assignRole: string; // 分配角色标题
    moreData = { morebutton: true,
        buttons: [
            {key: 'Overview' , value: '查看概况'},
            {key: 'Authority' , value: '权限配置'}
        ]
    }

    test: string;
    isNull: boolean; // 是否存在角色成员
    memberdata=[]
    roleAddModal = false; // 新增弹框
    list: any[] = []; // 角色列表
    orgCodeChild: string;
    roleName: string; // 角色姓名
    isrootChild: boolean; // 判断是角色还是角色组
    ngOnInit() {
        this.roleGuid = this.activatedRoute.snapshot.params.id; // 拿到父组件传过来的组织机构的guid来进行操作
        if(this.roleGuid === 'root') {
            this.isrootChild = false;
        } else {
            this.isrootChild = true;
        }
        if(this.data.length !== 0){
            this.isNull = false;
        }else{
            this.isNull = true;
        }
        this.getData(); // 只会触发一次，但是ngchanges并不会触发咋办
        this.getRoleInfo();
        this.dictQueryKey()
    }


    // 根据key查询业务字典
    dictQueryKey() {
        this.commondict.queryDictKey(appConfig.dictKeyList.operatorStatus)
            .subscribe((val) => {
                this.operType = val.result;
            })

        this.commondict.queryDictKey(appConfig.dictKeyList.empStatus)
            .subscribe((val) => {
                this.roleType = val.result;
            })
    }



    getRoleInfo() {
        this.utilityService.getData(appConfig.serverUrl  + appConfig.API.queryRoleById + '/' +  this.roleGuid)
            .subscribe(
                (val) => {
                    this.roleName = val.result.roleName;
                    this.reuseTabService.title = this.roleName + '下员工'
                    });
        // roleName
    }


    getData(options?) { // 初始化请求后台数据
        if (options) {
            this.pageIndex = 1;
        }
        this.page = {
            condition: this.objJson, // 搜索内容
            page: {
                current: this.pageIndex,
                size: this.operators.size,
                orderByField: 'guid',
                asc: false // asc 默认是true  升序排序，时间类型 用false， 降序
            }
        };
        this.utilityService.postData(appConfig.serverUrl  + appConfig.API.queryByRole + '/' + this.roleGuid , this.page)
            .subscribe(
                (val) => {
                    for (let i = 0; i <  val.result.records.length; i++) {
                        val.result.records[i].buttonData = [ {key: 'dels', value: '删除', if: false}];
                    }
                    this.data = val.result.records;
                    this.total = val.result.total;
                },
                error => {
                    this.nznot.create('error', error.code , error.msg);
                }
            );
        for(var i = 0; i < this.data.length; i ++) {
            this.data[i].buttonData = [ {key: 'dels', value: '删除', if: false}]
        }

    }

    // 想一下，能否把这三个方法封装到一个ts里面，引入即可，不然每次都写着三个方法不太现实。
    // 列表组件传过来的内容
    addHandler(event) {
        if (event === 'add') {
            this.roleAddModal = true;  // 此时点击了列表组件的新增，打开模态框
            this.selectArray = [];
            this.selectType = 'empName'
            this.assignRole = '为角色【' + this.roleName + '】分配操作员'
            this.getroleList()
        } else { // 代表修改，把修改的内容传递进去，重新渲染
            this.selectArray = [];
            this.roleAddModal = true;  // 此时点击了列表组件的新增，打开模态框
            this.assignRole = '为角色【' + this.roleName + '】分配操作员'
        }
    }

    // select更改方法
    selectChange(item) {
        this.orgChildList = [];
        this.orgCodeChild = '';
        if(item === 'org') {
            this.orgCode = '' ; // 清空
            // 查询所有机构
            this.utilityService.getData(appConfig.serverUrl  + appConfig.API.cascadeQueryAll)
                .subscribe(
                    (val) => {
                        this.orgList = val.result;
                    });
        } else {
            // 请求所有的员工
            this.getroleList();
        }
    }

    selectorgorgChange(guid) {
        for( let i = 0; i < this.orgList.length; i ++ ) {
            if(guid === this.orgList[i].guid) {
                this.orgChildList = this.orgList[i].children;
            }
        }
    }

    // 组织机构进行修改选择方法
    selectorgChange(guid) {
        this.utilityService.getData(appConfig.serverUrl  + appConfig.API.queryEmployeesByOrgId + '/' + guid + '/' + this.roleGuid)
            .subscribe(
                (val) => {
                    console.log(guid)
                    console.log(this.list)
                    const ret = [];
                    for (let i = 0; i < val.result.length; i++) {
                        ret.push({
                            key: i.toString(),
                            title:val.result[i]['empName'], // 名称g
                            userId:val.result[i]['userId'], // 操作员userId
                            guid:val.result[i]['guidOperator'], // 操作员guid
                            status: val.result[i]['exit'], // 状态，用来保存给后台的标识
                            description: val.result[i]['empName'],  // 描述
                            direction: val.result[i]['exit'] === 'true' ? 'left' : 'right', // 在左边还是右边，协商的字段 exit，给true代表左边未分配的，false代表右边，已分配的
                        });
                    }
                    this.list = ret;
                });
         /*   .subscribe(
                (val) => {

                });*/
    }

    // 根据父机构查询子机构
    selectorgchildChange(guid) {
        // 请求写在这里即可
    }

    // 右侧操作删除按钮
    buttonEvent(event) {
        console.log(event)
        if(event.names.key === 'dels') {
            this.modal.open({
                title: '是否删除',
                content: '您确认要删除该操作员吗',
                okText: '确定',
                cancelText: '取消',
                onOk: () => {
                    // 换接口即可
                    let deletaObj = {
                        operatorIdList: [event.guid],
                        roleIdList: [this.roleGuid]
                    }
                    this.utilityService.postData(appConfig.serverUrl + appConfig.API.batchDelete, deletaObj )
                        .subscribe(
                            (val) => {
                                this.getData()
                                this.nznot.create('success', val.msg , val.msg);
                            },
                            (error)=> {
                                this.nznot.create('error', error.msg , error.msg);
                            });

                },
                onCancel: () => {
                    console.log('失败');
                }
            });
        }
    }

    // 批量删除
    deleteBatch(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除这' + event.length + '个操作员吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                let delarray = [];
                for( let i = 0; i < event.length; i++) {
                    delarray.push(event[i].guid);
                }
                let deletaObj = {
                    operatorIdList:delarray ,
                    roleIdList: [this.roleGuid]
                }
                this.utilityService.postData(appConfig.serverUrl + appConfig.API.batchDelete, deletaObj )
                    .subscribe(
                        (val) => {
                            this.getData();
                            this.selectedRows = []
                            this.nznot.create('success', val.msg , val.msg);
                        },
                        (error)=> {
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                this.selectedRows = []
                this.getData()
            }
        });

    }



    // 工程穿梭框
    copyList = []; // 拷贝数组
    getroleList(){
     this.utilityService.getData(appConfig.serverUrl + appConfig.API.queryEntryEmp + '/' + this.roleGuid)
            .subscribe(
                (val) => {
                    console.log(val)
                     const ret = [];
                       for (let i = 0; i < val.result.length; i++) {
                                ret.push({
                                    key: i.toString(),
                                    title:val.result[i]['empName'], // 名称g
                                    userId:val.result[i]['userId'], // 操作员userId
                                    guid:val.result[i]['guidOperator'], //操作员guid
                                    status: val.result[i]['exit'], // 状态，用来保存给后台的标识
                                    description: val.result[i]['empName'],  // 描述
                                    direction: val.result[i]['exit'] === 'true' ? 'left' : 'right', // 在左边还是右边，协商的字段 exit，给true代表左边未分配的，false代表右边，已分配的
                                });
                            }
                            localStorage.setItem('copy', JSON.stringify(ret))
                            this.list = ret;
                });
}


    subPro = [];
    selectArray  = []; // 默认是空
    selecstArray  = []; // 默认是空
    change(ret: any) {
        console.log(ret)
        for(let i = 0 ; i < ret.list.length; i++){
            ret.list[i]['status'] =  ret.to
            ret.list[i]['direction'] =  ret.to
        }
    }

    //新增提交
    subAddrole(){
        this.copyList = JSON.parse(localStorage.getItem('copy')); // 后台返回状态
        for(let i = 0; i < this.list.length; i++) {
            for(let s = 0; s < this.copyList.length; s++) {
                if(this.list[i].userId === this.copyList[s].userId) {
                   if(this.list[i].direction != this.copyList[s].direction) { // 数据进行过修改
                       this.selectArray.push(this.list[i])
                   }
                }
            }
        }
        let marArray = [];
        for(let i = 0; i < this.selectArray.length; i ++) {
            let obj = {
                operateId: this.selectArray[i].guid,
                checed: this.selectArray[i].status === 'right'? false: true
            };
            marArray.push(obj)
        }


        let jsonData = {
            list: marArray,
            roleId: this.roleGuid
        }
        this.utilityService.postData(appConfig.serverUrl  + appConfig.API.batchAddOperators ,jsonData)
            .subscribe(
                (val) => {
                    this.roleAddModal = false;
                    this.nznot.create('success', val.msg , val.msg);
                    this.getData();
                } ,
                (error) => {
                    this.nznot.create('error', error.code,error.msg);
                    this.roleAddModal = false;
                    this.getData();

                }
            );
    }

    filterOption(inputValue, option) {
        return option.description.indexOf(inputValue) > -1;
    }

  searchpro(ret: any) {
    console.log('nzSearchChange', ret);
  }

    select(ret: any) {
    }




    // 列表传入的翻页数据
    monitorHandler(event) {
        this.pageIndex = event;
        this.getData();
    }

    // 接受子组件删除的数据 单条还是多条
    deleatData(event) {

    }


    // 列表按钮方法
    buttonDataHandler(event) {
        console.log(event); // 根据event.value来判断不同的请求，来获取结果和方法或者进行路由的跳转
        if (event.value ===  'Authority') {
            console.log(event.key);
        }

        if (event.value ===  'Overview') {
            console.log(event.key);
        }

    }



    selectedRow(event) { // 选中方法，折叠层按钮显示方法
        console.log(event);
    }



    // 处理行为代码，跳转、弹出框、其他交互
    isActive(event) {


        // 路由跳转
        this.router.navigate(['APPlication'],{ queryParams: { name: event } });
    }


    objJson = {};
    // 搜索框
    search() {
        this.objJson = this.operators;
        this.getData(this.operators);
    }

    reset() {
      this.operators = new OperaRoleModule();
      this.objJson = {};
      this.getData();
    }

    // 弹出框保存组件
    save() {
        console.log(this.operators);
        // 添加了两条数据
        this.data = [
            {'id': 1, 'operatorName': '汪波', 'userId': 'wangbo', 'operatorStatus': '正常', 'empCode': 'emp001', 'empStatus': '入职', 'guidOrg': '北京银行' },
            {'id': 2, 'operatorName': '汪波', 'userId': 'wangbo', 'operatorStatus': '正常', 'empCode': 'emp001', 'empStatus': '入职', 'guidOrg': '北京银行' },
            {'id': 3, 'operatorName': '汪波', 'userId': 'wangbo', 'operatorStatus': '正常', 'empCode': 'emp001', 'empStatus': '入职', 'guidOrg': '北京银行' },
            {'id': 4, 'operatorName': '汪波', 'userId': 'wangbo', 'operatorStatus': '正常', 'empCode': 'emp001', 'empStatus': '入职', 'guidOrg': '北京银行' }
        ];
        this.modalVisible = false;
    }

}
